<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    class="demo-ruleForm"
    style="width: 100%;"
  >
    <el-row>
      <el-col :span="20">
        <el-form-item label="" prop="user">
          <el-input v-model="ruleForm.user" autocomplete="off" placeholder="请输入账号" style="height:40px">
            <template #prefix>
              <el-icon class="iconfont icon-zhanghao" />
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="20">
        <el-form-item label="" prop="pass">
          <el-input
            v-model="ruleForm.pass"
            style="height:40px"
            placeholder="请输入密码"
            type="password"
            autocomplete="off"
          >
            <template #prefix>
              <el-icon class="iconfont icon-mima" />
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="20">
        <el-form-item>
          <el-button type="primary" class="submit-btn" @click="submitForm(ruleFormRef)">
            登录
          </el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  pass: '',
  user: '',
})

const validateUser = (rules:object, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}
const validatePass = (rules:object, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}
const rules = reactive({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  user: [{ validator: validateUser, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      sessionStorage.setItem('token', 'admin')
      setTimeout(() => {
        router.replace({ path: '/home' })
      }, 1000)
    } else {
      console.log('error submit!')
      return false
    }
  })
}
</script>
<style lang="less" scoped>
.submit-btn{
  margin: 0 auto;
  width: 80%;
  height: 40px;
  border-radius: 20px;
}
</style>
